﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YY.UI.BaseDataSvc;
using YY.Common;
using System.Configuration;
using System.IO;
using Yogesh.ExcelXml;

namespace YY.UI
{
    public partial class EditOrderFrm : BaseFrm
    {
        /// <summary>
        /// 编辑模式时，当前OrderId
        /// </summary>
        public int OrderId { get; set; }

        bool _EditMode = false;
        /// <summary>
        /// 窗体是否编辑模式
        /// </summary>
        public bool EditMode
        {
            get { return this._EditMode; }
            set { this._EditMode = value; showExtTabs(value); }
        }

        /// <summary>
        /// 业务源数据临时变量
        /// </summary>
        IEnumerable<TB_User> bizMans = null;
        /// <summary>
        /// 通用分类数据临时变量
        /// </summary>
        IEnumerable<TB_Options> options = null;
        /// <summary>
        /// 客户源数据临时变量
        /// </summary>
        IEnumerable<TB_Clients> clients = null;

        /// <summary>
        /// 编辑模式当前工作单临时变量
        /// </summary>
        TB_Order _Order = null;

        /// <summary>
        /// 当前工作单的拖车信息
        /// </summary>
        TB_Trailer _Trailer = null;

        /// <summary>
        /// 当前工作单的报关信息
        /// </summary>
        TB_Customs _Customs = null;

        /// <summary>
        /// 费用临时变量
        /// </summary>
        TB_Fee _Fee = null;

        public EditOrderFrm()
        {
            InitializeComponent();
            YY.Common.EventCommon.CaseUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateXHDgv);
            YY.Common.EventCommon.CargoUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateHWDgv);
            YY.Common.EventCommon.YSUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateYSDgv);
            YY.Common.EventCommon.YFUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateYFDgv);
            YY.Common.EventCommon.WorkFlowUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateWorkflow);
            this.BaseDataProxy = new YY.UI.BaseDataSvc.BaseDataClient();
        }

        private void EditOrderFrm_Load(object sender, EventArgs e)
        {
            initDgv();
            showExtTabs(this.EditMode);
            this.BaseDataProxy.Open();
            options = this.BaseDataProxy.FindOptions(null, null, null);
            initBaseInfo();
            if (this.EditMode)
            {
                getBaseInfo();
                if (SysLoginUserInfo.Role != (int)EnumCommon.SysRoleType.客服员 && SysLoginUserInfo.Role != (int)EnumCommon.SysRoleType.管理员 && SysLoginUserInfo.Role != (int)EnumCommon.SysRoleType.财务员)
                {
                    setOrderBodyReadOnly(true, this.tabControl1, this.btnDownload);
                }
            }
        }

        #region 控件显示数据初始化

        /// <summary>
        /// 设置扩展信息TAB控件是否显示
        /// </summary>
        /// <param name="show"></param>
        private void showExtTabs(bool show)
        {
            this.lblCode.Visible = show;
            this.txtBoxCode.Visible = show;
            this.lblStatus.Visible = show;
            this.cbBoxOrderStatus.Visible = show;
            if (show)
            {
                this.tabPage2.Parent = this.tabControl1;
                this.tabPage3.Parent = this.tabControl1;
                this.tabPage4.Parent = this.tabControl1;
                this.tabPage5.Parent = this.tabControl1;
                this.tabPage6.Parent = this.tabControl1;
            }
            else
            {
                this.tabPage2.Parent = null;
                this.tabPage3.Parent = null;
                this.tabPage4.Parent = null;
                this.tabPage5.Parent = null;
                this.tabPage6.Parent = null;
            }
        }

        /// <summary>
        /// DataGridView初始化
        /// </summary>
        private void initDgv()
        {
            initWorkFlowDgvColumns();
            initBGDgvColumns();
            initCaseDgvColumns();
            initAttachDgvColumns();
            initFeeDgvColumns();
        }

        /// <summary>
        /// 设置工作单内容只读状态
        /// </summary>
        private void setOrderBodyReadOnly(bool readOnly, Control pControl, Control excludeControl)
        {
            foreach (Control c in pControl.Controls)
            {
                if (c != excludeControl)
                {
                    Type t = c.GetType();
                    if (t.Equals(typeof(TextBox)))
                    { ((TextBox)c).ReadOnly = readOnly; }
                    else if (t.Equals(typeof(ComboBox)))
                    { ((ComboBox)c).Enabled = !readOnly; }
                    else if (t.Equals(typeof(DateTimePicker)))
                    { ((DateTimePicker)c).Enabled = !readOnly; }
                    else if (t.Equals(typeof(CheckBox)))
                    { ((CheckBox)c).Enabled = !readOnly; }
                    else if (t.Equals(typeof(Button)))
                    { ((Button)c).Enabled = !readOnly; }
                    else if (t.Equals(typeof(DataGridView)))
                    {
                        DataGridView dgv = ((DataGridView)c);
                        foreach (DataGridViewColumn dgvCol in dgv.Columns)
                            dgvCol.ReadOnly = readOnly;
                    }
                    else
                        setOrderBodyReadOnly(readOnly, c, excludeControl);
                }
            }
        }

        #region 基本信息控制部分
        private void initBaseInfo()
        {
            bizMans = this.BaseDataProxy.FindUsers(null, null);

            initAgent();

            initBizmans();

            initClients();

            Common.BindEnumToComboBox(this.cbBoxOrderStatus, typeof(EnumCommon.OrderStatus), null);
            this.cbBoxOrderStatus.Enabled = false;

            Common.BindOptionsComboBox(this.cbBoxStartPort, this.options, EnumCommon.OptionType.港口);
            this.cbBoxStartPort.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxImptAndExpt, this.options, EnumCommon.OptionType.进出口类型);
            this.cbBoxImptAndExpt.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxEndPort, this.options, EnumCommon.OptionType.港口);
            this.cbBoxEndPort.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxStowageMethod, this.options, EnumCommon.OptionType.装柜形式);
            this.cbBoxStowageMethod.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

        }

        /// <summary>
        /// 初始化当前操作员
        /// </summary>
        private void initAgent()
        {
            this.cbBoxAgent.Enabled = false;
            TB_User currentUser = new TB_User();
            currentUser.code = SysLoginUserInfo.UserCode;
            currentUser.id = SysLoginUserInfo.UserId;
            currentUser.userName = SysLoginUserInfo.UserName;
            this.cbBoxAgent.Items.Clear();
            this.cbBoxAgent.DisplayMember = "userName";
            this.cbBoxAgent.ValueMember = "id";
            this.cbBoxAgent.Items.Add(currentUser);
            this.cbBoxAgent.SelectedIndex = 0;
            this.txtBoxOpContact.Text = currentUser.mobile;
        }

        /// <summary>
        /// 初始化业务员数据
        /// </summary>
        private void initBizmans()
        {
            if (bizMans.Any())
            {
                IEnumerable<TB_User> datas = bizMans.Where(p => p.role == (int)EnumCommon.SysRoleType.业务员 || p.role == (int)EnumCommon.SysRoleType.主管经理);
                Common.ComboBoxBindDatas<TB_User>(this.cbBoxBizmans, datas, "userName", "id");
            }
        }

        /// <summary>
        /// 初始化客户数据
        /// </summary>
        private void initClients()
        {
            this.clients = this.BaseDataProxy.FindClients(null, null, null, null, null);
            Common.ComboBoxBindDatas<TB_Clients>(this.cbBoxClient, clients, "fullName", "id");
        }

        //初始化工作流数据列
        private void initWorkFlowDgvColumns()
        {
            this.dgvWorkflow.AutoGenerateColumns = false;
            this.dgvWorkflow.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "Id", "工作流Id", false, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "OrderId", "所属单据Id", false, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "FlowStatus", "环节", true, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "Operator", "处理人", true, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "HandleText", "处理情况", true, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "OPTime", "处理时间", true, true, null);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "Comment", "处理意见", true, true, 200);
            Common.AddDgvColumn(this.dgvWorkflow, new DataGridViewTextBoxColumn(), "NextOperator", "下一环节处理人", true, true, 150);
        }
        /// <summary>
        /// 加载工作单基本信息
        /// </summary>
        private void getBaseInfo()
        {
            this._Order = this.BaseDataProxy.GetOrder(this.OrderId);
            if (this._Order != null)
            {
                this.txtBoxCCode.Text = this._Order.cCode;
                if (this.bizMans != null)
                {
                    this.cbBoxAgent.Items.Clear();
                    TB_User agent = this.bizMans.SingleOrDefault(p => p.id == this._Order.agent);
                    this.cbBoxAgent.Items.Add(agent);
                    this.cbBoxAgent.SelectedItem = agent;

                    this.cbBoxBizmans.SelectedItem = this.bizMans.SingleOrDefault(p => p.id == this._Order.@operator);
                }
                if (this.clients != null)
                    this.cbBoxClient.SelectedItem = this.clients.SingleOrDefault(p => p.id == this._Order.client);
                this.txtBoxContactInfo.Text = this._Order.contactInfo;
                if (this._Order.customsDeadline != null)
                    this.dtpCustomsDeadline.Value = Convert.ToDateTime(this._Order.customsDeadline);
                this.ckBoxHasInvoice.Checked = this._Order.hasInvoice;
                this.ckBoxHasTrailer.Checked = this._Order.hasTrailer;

                Common.SelectedOptionsComboBox(this.cbBoxImptAndExpt, this.options, EnumCommon.OptionType.进出口类型, this._Order.imptAndExpt);
                this.txtBoxInvoiceHeader.Text = this._Order.invoiceHeader;
                this.ckBoxIsCustoms.Checked = this._Order.isCustoms;
                this.ckBoxIsOcean.Checked = this._Order.isOcean;
                this.txtBoxMemo.Text = this._Order.memo;
                this.dtpOrderDate.Value = this._Order.orderTime.Date;
                this.dtpOrderTime.Value = this._Order.orderTime;
                Common.SelectedOptionsComboBox(this.cbBoxStartPort, this.options, EnumCommon.OptionType.港口, this._Order.startPort);
                Common.SelectedOptionsComboBox(this.cbBoxEndPort, this.options, EnumCommon.OptionType.港口, this._Order.endPort);
                Common.SelectedOptionsComboBox(this.cbBoxStowageMethod, this.options, EnumCommon.OptionType.装柜形式, this._Order.stowageMethod);
                this.txtBoxCode.Text = this._Order.code;

                //if (this._Order.isSubmit)
                //{                    
                //    Common.BindEnumToComboBox(this.cbBoxOrderStatus, typeof(EnumCommon.OrderStatus),
                //        new string[] { EnumCommon.OrderStatus.取消.ToString(), EnumCommon.OrderStatus.订舱录入.ToString(), EnumCommon.OrderStatus.接单确认.ToString(), 
                //    EnumCommon.OrderStatus.操作完成.ToString() }, this._Order.status);                    
                //}
                //else
                //    this.cbBoxOrderStatus.SelectedItem = this._Order.status;
                //this.cbBoxOrderStatus.Enabled = true;
                this.cbBoxOrderStatus.SelectedItem = this._Order.status;

                this.dgvWorkflow.DataSource = this.BaseDataProxy.FindWorkflow(this._Order.id);
            }
            else
            {
                MessageBox.Show("工作单数据加载异常！请与管理员联系！");
                this.tabControl1.Enabled = false;
            }
        }
        #endregion

        #region 拖车信息控制部分

        /// <summary>
        /// 初始化拖车信息
        /// </summary>
        private void initTCInfo()
        {
            Common.BindOptionsComboBox(this.cbBoxStowageArea, this.options, EnumCommon.OptionType.提柜堆场);
            this.cbBoxStowageArea.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxReturnPort, this.options, EnumCommon.OptionType.码头);
            this.cbBoxReturnPort.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxTCAgent, this.options, EnumCommon.OptionType.拖车行);
            this.cbBoxTCAgent.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.业务员)
                this.cbBoxTCAgent.Visible = false;

            this.txtBoxTCMemo.Text = "1、请准时到厂 2、请提干净、无残损的好柜";
        }


        /// <summary>
        /// 加载拖车信息
        /// </summary>
        private void getTCInfo()
        {
            this._Trailer = this.BaseDataProxy.GetTrailer(this._Order.id);
            if (this._Trailer != null)
            {
                Common.SelectedOptionsComboBox(this.cbBoxStowageArea, this.options, EnumCommon.OptionType.提柜堆场, this._Trailer.stowageArea);
                this.ckBoxIsPonderation.Checked = this._Trailer.isPonderation;
                //if (this._Trailer.deadline != null)
                //{
                //原字段为时间类型，兼顾旧数据，如果旧数据还是日期，则限定格式输出
                DateTime deadlineDate;
                var isDate = DateTime.TryParse(this._Trailer.deadline, out deadlineDate);
                this.txtDeadline.Text = isDate ? deadlineDate.ToString("yyyy-MM-dd HH:mm") : this._Trailer.deadline;
                //this.dtpDeadlineTime.Value = Convert.ToDateTime(this._Trailer.deadline);
                //}
                Common.SelectedOptionsComboBox(this.cbBoxReturnPort, this.options, EnumCommon.OptionType.码头, this._Trailer.returnPort);
                this.txtBoxSpecs.Text = this._Trailer.specs;
                this.txtBoxOpContact.Text = this._Trailer.opContact;
                Common.SelectedOptionsComboBox(this.cbBoxTCAgent, this.options, EnumCommon.OptionType.拖车行, this._Trailer.agent);
                this.txtBoxTCAddress.Text = this._Trailer.address;
                this.txtBoxStowageContact.Text = this._Trailer.stowageContact;
                this.txtBoxTCMemo.Text = this._Trailer.memo;
                if (this._Trailer.charge != null)
                    this.txtBoxTCCharge.Text = Convert.ToDecimal(this._Trailer.charge).ToString();
            }
        }
        #endregion

        #region 报关信息控制部分

        /// <summary>
        /// 核销数据临时变量
        /// </summary>
        DataTable _DTHX = null;
        /// <summary>
        /// 初始化报关信息表格列
        /// </summary>
        private void initBGDgvColumns()
        {
            //初始化报关核销数据列
            this.dgvHX.AutoGenerateColumns = false;
            this.dgvHX.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "id", "核销Id", false, true, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "code", "单证抬头", true, false, null);

            DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
            cbc.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
            Common.BindEnumToDataGridViewComboBoxColumn(cbc, typeof(EnumCommon.CustomsStatus));
            Common.AddDgvColumn(this.dgvHX, cbc, "status", "状态", true, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "customsCode", "报关单号", true, false, null);

            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "corp", "报关单位", false, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewCalendarColumn(), "backTime", "回单时间", true, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewCalendarColumn(), "backClientTime", "退回客户时间", true, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "memo", "备注", true, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "corpName", "公司名称", false, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "title", "核销台头", false, false, null);
            Common.AddDgvColumn(this.dgvHX, new DataGridViewTextBoxColumn(), "customsId", "外键customsId", false, true, null);
        }

        /// <summary>
        /// 初始化报关信息
        /// </summary>
        private void initCustomsInfo()
        {

            Common.BindEnumToComboBox(this.cbBoxBGStatus, typeof(EnumCommon.CustomsStatus), EnumCommon.CustomsStatus.无报关.ToString());

            Common.BindOptionsComboBox(this.cbBoxBGAgent, this.options, EnumCommon.OptionType.报关行);
            this.cbBoxBGAgent.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.业务员)
                this.cbBoxBGAgent.Visible = false;

            Common.BindOptionsComboBox(this.cbBoxTransferType, this.options, EnumCommon.OptionType.中转类型);
            this.cbBoxTransferType.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxBGEndPort, this.options, EnumCommon.OptionType.港口);
            this.cbBoxBGEndPort.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
            this.txtBoxBGMemo.Text = "外拖/国际中转";
        }

        /// <summary>
        /// 加载工作单报关信息
        /// </summary>
        private void getCustomsInfo()
        {
            this._Customs = this.BaseDataProxy.GetCustoms(this._Order.id);
            if (this._Customs != null)
            {
                this.cbBoxBGStatus.Text = this._Customs.status;
                this.dtpApplyDate.Value = this._Customs.applyDate;
                this.txtBoxBGPassTime.Text = this._Customs.passTime == null ? null : Convert.ToDateTime(this._Customs.passTime).ToString("yyyy-MM-dd HH:mm");
                Common.SelectedOptionsComboBox(this.cbBoxBGAgent, this.options, EnumCommon.OptionType.报关行, this._Customs.agent);
                this.ckBoxIsOffer.Checked = this._Customs.isOffer;
                this.ckBoxIsCheck.Checked = this._Customs.isCheck;
                this.ckBoxIsPass.Checked = this._Customs.isPass;
                this.ckBoxNotice.Checked = this._Customs.isNotice;
                Common.SelectedOptionsComboBox(this.cbBoxTransferType, this.options, EnumCommon.OptionType.中转类型, this._Customs.transferType);
                this.ckBoxIsDrawback.Checked = this._Customs.isDrawback;
                this.ckBoxIsKdsk.Checked = this._Customs.isKdsk;
                this.txtBoxBGAddress.Text = this._Customs.address;
                this.txtBoxBGContactMan.Text = this._Customs.contactMan;
                this.txtBoxBGTel.Text = this._Customs.contactTel;
                this.txtBoxReceiver.Text = this._Customs.receiver;
                this.txtBoxNotifier.Text = this._Customs.notifier;
                this.txtBoxBoatName.Text = this._Customs.boatName;
                this.txtBoxRunNum.Text = this._Customs.runNum;
                this.txtBoxBoatCorp.Text = this._Customs.boatCorp;
                this.txtBoxStockholder.Text = this._Customs.stockholder;
                Common.SelectedOptionsComboBox(this.cbBoxBGEndPort, this.options, EnumCommon.OptionType.港口, this._Customs.endPort);
                this.txtBoxDestination.Text = this._Customs.destination;
                this.txtBoxBookingMemo.Text = this._Customs.bookingMemo;
                this.txtBoxBGMemo.Text = this._Customs.memo;
                this.txtBoxDemand.Text = this._Customs.demand;
                IEnumerable<TB_CheckOff> checkOffs = this.BaseDataProxy.GetCheckOffs(this._Customs.id);
                this._DTHX = checkOffs.ToDataTable();
                this.dgvHX.DataSource = this._DTHX;
            }
        }
        #endregion

        #region 货物信息控制部分
        /// <summary>
        /// 初始化货物信息表格列
        /// </summary>
        private void initCaseDgvColumns()
        {
            this.dgvXH.AutoGenerateColumns = false;
            this.dgvXH.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "id", "箱号Id", false, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "code", "箱号", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "model", "箱型", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "title", "封号", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "carNo", "车牌号", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "check", "查验封", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "trailer", "拖车", true, true, null);
            //Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "motorcade", "车队", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "driver", "司机", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "tel", "电话", true, true, null);
            Common.AddDgvColumn(this.dgvXH, new DataGridViewTextBoxColumn(), "memo", "备注", true, true, null);

            this.dgvHW.AutoGenerateColumns = false;
            this.dgvHW.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "id", "货物Id", false, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "case", "货物所属箱号id", false, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "cargoName", "货物名称", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "amount", "数量", true, true, null);

            //Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "packageType", "包装种类id", false, true, null);
            //DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
            //cbc.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
            //Common.BindOptionsDataGridViewComboBoxColumn(cbc, this.options, EnumCommon.OptionType.包装种类);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "packageType", "包装种类id", false, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "", "包装种类", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "hairWeight", "毛重", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "netWeight", "净重", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "volume", "体积", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "caseAmount", "箱量", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "marker", "唛头", true, true, null);
            Common.AddDgvColumn(this.dgvHW, new DataGridViewTextBoxColumn(), "memo", "备注", true, true, null);


            //this.btnAddHW.Enabled = false;
            //this.btnDeleteHW.Enabled = false;
        }

        DataTable _DTXH = null;
        DataTable _DTHW = null;
        /// <summary>
        /// 加载箱号信息
        /// </summary>
        private void getCaseInfo()
        {
            IEnumerable<TB_Case> cs = this.BaseDataProxy.GetCases(this._Order.id);
            this._DTXH = cs.ToDataTable();
            this.dgvXH.DataSource = this._DTXH;
            if (this.dgvXH.RowCount > 0)
                this.dgvXH.Rows[0].Selected = true;
        }

        /// <summary>
        /// 加载货物信息
        /// </summary>
        private void getCargoInfo()
        {
            if (this.dgvXH.CurrentRow != null)
            {
                IEnumerable<TB_Cargo> cargos = this.BaseDataProxy.GetCargos(Convert.ToInt32(this.dgvXH.CurrentRow.Cells[0].Value));
                this._DTHW = cargos.ToDataTable();
                this.dgvHW.DataSource = this._DTHW;
            }
        }
        #endregion

        #region 文件管理部分
        private void initAttachDgvColumns()
        {
            this.dgvAttach.AutoGenerateColumns = false;
            this.dgvAttach.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dgvAttach, new DataGridViewTextBoxColumn(), "id", "文件id", false, true, null);
            Common.AddDgvColumn(this.dgvAttach, new DataGridViewTextBoxColumn(), "attachName", "文件名称", true, true, 200);
            Common.AddDgvColumn(this.dgvAttach, new DataGridViewTextBoxColumn(), "size", "文件大小", true, true, 100);
            Common.AddDgvColumn(this.dgvAttach, new DataGridViewTextBoxColumn(), "ext", "文件类型", true, true, 100);
            Common.AddDgvColumn(this.dgvAttach, new DataGridViewTextBoxColumn(), "createTime", "上传时间", true, true, 100);
        }

        DataTable _DTAttach = null;
        /// <summary>
        /// 加载文件信息
        /// </summary>
        private void getAttachInfo()
        {
            IEnumerable<TB_Attach> attachs = this.BaseDataProxy.GetAttachs(this._Order.id);
            this._DTAttach = attachs.ToDataTable();
            this.dgvAttach.DataSource = this._DTAttach;
        }
        #endregion

        #region 费用管理部分
        /// <summary>
        /// 加载费用列表架构
        /// </summary>
        private void initFeeDgvColumns()
        {
            bool visible = true;
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.业务员)
                visible = false;

            this.dgvYS.AutoGenerateColumns = false;
            this.dgvYS.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
            DataGridViewCheckBoxHeaderCell cbHeader = new DataGridViewCheckBoxHeaderCell();
            colCB.HeaderCell = cbHeader;
            Common.AddDgvColumn(this.dgvYS, colCB, "", "", true, false, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "id", "应收id", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "item", "费用项目Id", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "", "应收费目", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "amount", "金额", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "unit", "币制", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "unitName", "币制", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "target", "结算对象id", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "targetName", "结算对象", visible, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "code", "账单号", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewCheckBoxColumn(), "isVerify", "审核", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "verifyMan", "审核人", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewCalendarColumn(), "verifyTime", "审核日期", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "operator", "制单人", false, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewCalendarColumn(), "createTime", "制单日期", true, true, null);
            Common.AddDgvColumn(this.dgvYS, new DataGridViewTextBoxColumn(), "memo", "备注", true, true, null);

            this.dgvYF.AutoGenerateColumns = false;
            this.dgvYF.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            colCB = new DataGridViewCheckBoxColumn();
            cbHeader = new DataGridViewCheckBoxHeaderCell();
            colCB.HeaderCell = cbHeader;
            Common.AddDgvColumn(this.dgvYF, colCB, "", "", true, false, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "id", "应付id", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "target", "结算对象id", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "item", "费用项目id", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "", "应付费目", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "amount", "金额", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "unit", "币制", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "unitName", "币制", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "targetName", "结算对象", visible, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "code", "账单号", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewCheckBoxColumn(), "isVerify", "审核", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "verifyMan", "审核人", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewCalendarColumn(), "verifyTime", "审核日期", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "operator", "制单人", false, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewCalendarColumn(), "createTime", "制单日期", true, true, null);
            Common.AddDgvColumn(this.dgvYF, new DataGridViewTextBoxColumn(), "memo", "备注", true, true, null);
        }

        DataTable _DTYS = null;
        DataTable _DTYF = null;
        /// <summary>
        /// 加载费用信息
        /// </summary>
        private void getFeeInfo()
        {
            IEnumerable<TB_Fee> fees = this.BaseDataProxy.GetFees(this._Order.id);
            this._DTYS = fees.Where(p => p.feeType == (short)EnumCommon.FeeType.应收).ToDataTable();
            this.dgvYS.DataSource = this._DTYS;

            this._DTYF = fees.Where(p => p.feeType == (short)EnumCommon.FeeType.应付).ToDataTable();
            this.dgvYF.DataSource = this._DTYF;
        }
        #endregion

        #endregion

        #region 委托事件回调
        /// <summary>
        /// 箱号更新回调
        /// </summary>
        /// <param name="o"></param>
        /// <param name="arg"></param>
        private void updateXHDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Case> argObj = (CommonEventArg<TB_Case>)arg;
                if (argObj.OpType == Common.OperateType.Add)
                {
                    getCaseInfo();
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    getCaseInfo();
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                    deleteXH(false, argObj.t.id);
            }
        }
        /// <summary>
        /// 货物更新回调
        /// </summary>
        /// <param name="o"></param>
        /// <param name="arg"></param>
        private void updateHWDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Cargo> argObj = (CommonEventArg<TB_Cargo>)arg;
                if (argObj.OpType == Common.OperateType.Add)
                {
                    getCargoInfo();
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    getCargoInfo();
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                    deleteHW(false, argObj.t.id);
            }
        }

        private void updateYSDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Fee> argObj = (CommonEventArg<TB_Fee>)arg;
                if (argObj.OpType == Common.OperateType.Add)
                {
                    getFeeInfo();
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    getFeeInfo();
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                    deleteFee(this.dgvYS, false, this._DTYS, argObj.t.id);
            }
        }
        private void updateYFDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Fee> argObj = (CommonEventArg<TB_Fee>)arg;
                if (argObj.OpType == Common.OperateType.Add)
                {
                    getFeeInfo();
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    getFeeInfo();
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                    deleteFee(this.dgvYF, false, this._DTYF, argObj.t.id);
            }
        }

        private void updateWorkflow(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Workflow> argObj = (CommonEventArg<TB_Workflow>)arg;
                if (argObj.OpType == Common.OperateType.Update)
                    getBaseInfo();
            }
        }
        #endregion

        #region 按钮控件事件方法

        /// <summary>
        /// 清除TabPage内容
        /// </summary>
        /// <param name="tb"></param>
        private void clearTabPageFormInput(TabPage tb)
        {
            for (int i = 0; i < tb.Controls.Count; i++)
            {
                //if (tb.Controls[i].Name.StartsWith(s))
                //{
                Type t = tb.Controls[i].GetType();
                //if (t.Equals(typeof(ComboBox)))
                //    ((ComboBox)tb.Controls[i]).SelectedItem = null;
                //else 
                if (t.Equals(typeof(TextBox)))
                    ((TextBox)tb.Controls[i]).Text = null;
                //else if (t.Equals(typeof(DataGridView)))
                //    ((DataGridView)tb.Controls[i]).DataSource = null;
                //}

            }
        }

        /// <summary>
        /// 通用分类选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void optionCbBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                EnumCommon.OptionType ot = (EnumCommon.OptionType)cbBox.Tag;
                if (this.options != null)
                {
                    TB_Options[] os = this.options.Where(p => p.type == ot.ToString()).Where(p => p.name.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchOption(cbBox, os, this, ot);
                }
            }
        }

        /// <summary>
        /// 用户选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBoxBizmans_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.bizMans != null)
                {
                    IEnumerable<TB_User> datas = bizMans.Where(p => p.role == (int)EnumCommon.SysRoleType.业务员 || p.role == (int)EnumCommon.SysRoleType.主管经理);
                    datas = datas.Where(p => p.userName.Contains(cbBox.Text) || p.code.Contains(cbBox.Text));
                    Common.ComboBoxMatchUser(cbBox, datas.ToArray(), this);
                }
            }
        }

        /// <summary>
        /// 客户选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBoxClient_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.clients != null)
                {
                    TB_Clients[] datas = this.clients.Where(p => p.fullName.Contains(cbBox.Text) || p.shortName.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchClient(cbBox, datas, this);
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.tabControl1.SelectedIndex)
            {
                case 1:
                    initTCInfo();
                    getTCInfo();
                    break;
                case 2:
                    initCustomsInfo();
                    getCustomsInfo();
                    break;
                case 3:
                    getCaseInfo();
                    break;
                case 4:
                    getAttachInfo();
                    break;
                case 5:
                    getFeeInfo();
                    break;
                default:
                    //initBaseInfo();
                    getBaseInfo();
                    break;
            }
        }

        private void tsBtnAdd_Click(object sender, EventArgs e)
        {
            initNewOrder();
        }

        /// <summary>
        /// 初始化新单
        /// </summary>
        private void initNewOrder()
        {
            showExtTabs(false);
            this.tabControl1.SelectedIndex = 0;
            clearTabPageFormInput(this.tabPage1);
            this.dgvWorkflow.DataSource = null;
            this.EditMode = false;
            this.OrderId = 0;
            this._Order = null;
        }

        #region 基本信息

        /// <summary>
        /// 修改流程状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBoxOrderStatus_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (this.EditMode && this._Order != null)
            {
                bool permit = false;

                if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.管理员)
                    permit = true;
                else
                {
                    if (this._Order.isSubmit)
                    {
                        if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.财务员)
                            permit = true;
                    }
                    else
                    {
                        if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.客服员)
                            permit = true;
                    }
                }

                if (permit)
                {
                    if (MessageBox.Show("确认修改单据流程状态吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (updateOrderStatus(this.cbBoxOrderStatus.Text))
                        {
                            MessageBox.Show("单据流程已设置为 [" + this._Order.status + "] 状态！");
                            return;
                        }
                    }
                }

                this.cbBoxOrderStatus.SelectedItem = this._Order.status;
            }
        }

        /// <summary>
        /// 保存基本信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveBase_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtBoxCCode.Text))
            {
                MessageBox.Show("请输入提单号！");
                this.txtBoxCCode.Focus();
                return;
            }

            if (this.cbBoxBizmans.SelectedItem == null)
            {
                MessageBox.Show("请选择业务员！");
                this.cbBoxBizmans.Focus();
                return;
            }

            if (this.cbBoxClient.SelectedItem == null)
            {
                MessageBox.Show("请选择委托方！");
                this.cbBoxClient.Focus();
                return;
            }


            TB_Order order = new TB_Order();

            order.cCode = this.txtBoxCCode.Text;
            order.client = ((TB_Clients)this.cbBoxClient.SelectedItem).id;
            order.contactInfo = this.txtBoxContactInfo.Text;
            order.customsDeadline = this.dtpCustomsDeadline.Value;
            order.hasInvoice = this.ckBoxHasInvoice.Checked;
            order.hasTrailer = this.ckBoxHasTrailer.Checked;
            if (this.cbBoxImptAndExpt.SelectedItem != null)
                order.imptAndExpt = (this.cbBoxImptAndExpt.SelectedItem as TB_Options).id;
            order.invoiceHeader = this.txtBoxInvoiceHeader.Text;
            order.isClosed = false;
            order.isCustoms = this.ckBoxIsCustoms.Checked;
            order.isOcean = this.ckBoxIsOcean.Checked;
            order.memo = this.txtBoxMemo.Text;
            order.@operator = ((TB_User)this.cbBoxBizmans.SelectedItem).id;
            order.orderTime = this.dtpOrderDate.Value;//this.dtpOrderDate.Value.AddHours(this.dtpOrderTime.Value.Hour).AddMinutes(this.dtpOrderTime.Value.Minute).AddSeconds(this.dtpOrderTime.Value.Second);
            if (this.cbBoxStartPort.SelectedItem != null)
                order.startPort = (this.cbBoxStartPort.SelectedItem as TB_Options).id;
            if (this.cbBoxEndPort.SelectedItem != null)
                order.endPort = (this.cbBoxEndPort.SelectedItem as TB_Options).id;
            if (this.cbBoxStowageMethod.SelectedItem != null)
                order.stowageMethod = (this.cbBoxStowageMethod.SelectedItem as TB_Options).id;

            Common.OperateType opType = Common.OperateType.Add;

            var dupl = this.BaseDataProxy.FindOrders(false, null, this.txtBoxCCode.Text, null, null, null, null, null, null, null, null, null, null, null);
            if (dupl != null && dupl.Count() > 0)
            {
                if (!this.EditMode || (this.EditMode && dupl.Where(d => d.OrderId != this.OrderId).Count() > 0))
                {
                    MessageBox.Show("此单号已存在！");
                    return;
                }
            }

            if (this.EditMode)
            {
                //if ((int)Enum.Parse(typeof(EnumCommon.OrderStatus), this._Order.status) > 2)
                if (Common.BIZ_OrderIsSubmit(this._Order.id))
                {
                    MessageBox.Show("已提交财务审核单据不能修改！");
                    return;
                }

                order.code = this._Order.code;
                order.agent = this._Order.agent;
                order.deleteFlag = this._Order.deleteFlag;
                order.createTime = this._Order.createTime;
                order.id = this._Order.id;
                order.isClosed = this._Order.isClosed;
                order.status = this._Order.status;
                opType = Common.OperateType.Update;
                if (this.BaseDataProxy.UpdateOrder(order))
                {
                    CommonEventArg<TB_Order> arg = new CommonEventArg<TB_Order>(order, opType);
                    YY.Common.EventCommon.OnOrderUdDGVEvnt(sender, arg);
                    MessageBox.Show("基本信息已保存！");
                }
            }
            else
            {
                CodeRuleFrm.CodeRule codeRule = new CodeRuleFrm.CodeRule();
                codeRule.addParent = false;
                codeRule.autoCode = true;
                codeRule.autoFill = true;
                codeRule.header = ConfigurationManager.AppSettings["OrderCodeHeader"];
                codeRule.len = Convert.ToInt32(ConfigurationManager.AppSettings["SerialLen"]);
                order.agent = SysLoginUserInfo.UserId;
                order.code = this.BaseDataProxy.GetSerialNo(1, codeRule.header, codeRule.len, true, codeRule.autoFill, true);
                order.createTime = DateTime.Now;
                //order.status = EnumCommon.OrderStatus.订舱录入.ToString();
                int id = this.BaseDataProxy.AddOrder(order);
                if (id > 0)
                {
                    this.txtBoxCode.Text = order.code;
                    //this.cbBoxOrderStatus.Text = order.status;
                    this.OrderId = id;
                    this.EditMode = true;
                    order.id = id;
                    this._Order = order;
                    CommonEventArg<TB_Order> arg = new CommonEventArg<TB_Order>(order, opType);
                    YY.Common.EventCommon.OnOrderUdDGVEvnt(sender, arg);

                    if (MessageBox.Show("工作单基本信息已创建，是否继续添加拖车信息？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.tabControl1.SelectedTab = this.tabPage2;
                    }
                }
                else
                    MessageBox.Show("资料保存异常，请与管理员联系！");
            }
        }

        private void tsBtnDelete_Click(object sender, EventArgs e)
        {
            if (this.EditMode && this._Order != null)
            {
                if (MessageBox.Show("确认取消该工作单吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (Common.BIZ_OrderIsSubmit(this._Order.id))
                    {
                        MessageBox.Show("已提交财务审核单据不能修改！");
                        return;
                    }

                    MsgBoolean mb = this.BaseDataProxy.DeleteOrder(this._Order.id);
                    if (mb != null)
                    {
                        if (mb.Ok)
                        {
                            CommonEventArg<TB_Order> arg = new CommonEventArg<TB_Order>(this._Order, Common.OperateType.Delete);
                            YY.Common.EventCommon.OnOrderUdDGVEvnt(sender, arg);
                            MessageBox.Show("单据已被设置取消状态！");
                            initNewOrder();
                        }
                        else
                            MessageBox.Show(mb.Msg);
                    }
                    else
                        MessageBox.Show("单据取消异常！");
                }
            }
        }

        private void tsBtnSubmit_Click(object sender, EventArgs e)
        {
            //submitOrder(true,"提交");  
            if (this._Order != null)
            {
                EditWorkflowFrm frm = new EditWorkflowFrm();
                frm.Order = this._Order;
                frm.ShowDialog(this);
            }
        }

        private bool updateOrderStatus(string status)
        {
            this._Order.status = status;
            if (this.BaseDataProxy.UpdateOrder(this._Order))
            {
                CommonEventArg<TB_Order> arg = new CommonEventArg<TB_Order>(this._Order, Common.OperateType.Update);
                YY.Common.EventCommon.OnOrderUdDGVEvnt(this, arg);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 提交/退回工作单
        /// </summary>
        /// <param name="submit"></param>
        private void submitOrder(bool submit, string msgFlag)
        {
            if (this.EditMode && this._Order != null)
            {
                if (MessageBox.Show("确认" + msgFlag + "工作单吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int status = (int)Enum.Parse(typeof(EnumCommon.OrderStatus), this._Order.status);
                    bool reDo = false;
                    EnumCommon.OrderStatus value = EnumCommon.OrderStatus.财务审核;
                    if (submit)
                    {
                        if (status > 2)
                            reDo = true;
                    }
                    else
                    {
                        value = EnumCommon.OrderStatus.操作完成;
                        if (status < 3)
                            reDo = true;
                    }

                    if (reDo)
                    {
                        MessageBox.Show("不能重复" + msgFlag + "！");
                        return;
                    }


                    this._Order.isSubmit = submit;
                    if (updateOrderStatus(value.ToString()))
                    {
                        MessageBox.Show("工作单已" + msgFlag + "！");
                        initBaseInfo();
                        getBaseInfo();
                        //置换单据只读状态
                    }
                    else
                        MessageBox.Show("工作单" + msgFlag + "异常！");
                }
            }
        }

        private void cbBoxClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cbBox = sender as ComboBox;
            if (cbBox.SelectedItem != null)
            {
                TB_Clients c = cbBox.SelectedItem as TB_Clients;
                this.txtBoxContactInfo.Text = c.contactMan + " " + c.tel;
                this.txtBoxInvoiceHeader.Text = c.fullName;
            }
        }
        #endregion

        #region 拖车
        /// <summary>
        /// 保存拖车信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveTC_Click(object sender, EventArgs e)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (this.cbBoxStowageArea.SelectedItem == null)
            {
                MessageBox.Show("请选择提柜堆场！");
                this.cbBoxStowageArea.Focus();
                return;
            }

            if (this.cbBoxTCAgent.SelectedItem == null)
            {
                MessageBox.Show("请选择拖车行！");
                this.cbBoxAgent.Focus();
                return;
            }
            TB_Trailer trailer = new TB_Trailer();
            trailer.address = this.txtBoxTCAddress.Text;
            trailer.agent = (this.cbBoxTCAgent.SelectedItem as TB_Options).id;
            //trailer.deadline = this.dtpDeadline.Value.AddHours(this.dtpDeadlineTime.Value.Hour).AddMinutes(this.dtpDeadlineTime.Value.Minute).AddSeconds(this.dtpDeadlineTime.Value.Second); ;
            trailer.deadline = this.txtDeadline.Text;
            trailer.isPonderation = this.ckBoxIsPonderation.Checked;
            trailer.memo = this.txtBoxTCMemo.Text;
            trailer.opContact = this.txtBoxOpContact.Text;
            if (!string.IsNullOrEmpty(this.txtBoxTCCharge.Text))
                trailer.charge = decimal.Parse(this.txtBoxTCCharge.Text);
            //trailer.orderId = this._Order.id;
            if (this.cbBoxReturnPort.SelectedItem != null)
                trailer.returnPort = (this.cbBoxReturnPort.SelectedItem as TB_Options).id;
            trailer.specs = this.txtBoxSpecs.Text;
            trailer.stowageArea = (this.cbBoxStowageArea.SelectedItem as TB_Options).id;
            trailer.stowageContact = this.txtBoxStowageContact.Text;
            bool ok = this.BaseDataProxy.UpdateTrailer(this._Order.id, new TB_Trailer[] { trailer });
            if (ok)
            {
                MessageBox.Show("拖车信息已保存！");
            }
            else
                MessageBox.Show("拖车信息保存失败！");
        }

        private void btnClearTC_Click(object sender, EventArgs e)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (MessageBox.Show("确认删除拖车信息吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                bool ok = this.BaseDataProxy.UpdateTrailer(this._Order.id, null);
                if (ok)
                    MessageBox.Show("拖车信息已清除！");
                else
                    MessageBox.Show("拖车信息清除失败！");
                clearTabPageFormInput(this.tabPage2);
            }
        }

        private void btnPrintTC_Click(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["OrderCodeHeader"] == "YH")
                printYHPCDPre();
            else
                printYYTCWTS();
        }



        private void txtBoxTCCharge_KeyPress(object sender, KeyPressEventArgs e)
        {
            //限制只能输入0-9的数字，退格键，小数点
            if (((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57) || e.KeyChar == 8 || e.KeyChar == 46)
            { }
            else
                e.Handled = true;
        }

        private void ckBoxIsPonderation_CheckedChanged(object sender, EventArgs e)
        {
            var str = "3、要求过磅";
            if (this.ckBoxIsPonderation.Checked & !this.txtBoxTCMemo.Text.Contains(str))
                this.txtBoxTCMemo.Text += str;
            else if (!this.ckBoxIsPonderation.Checked & this.txtBoxTCMemo.Text.Contains(str))
                this.txtBoxTCMemo.Text = this.txtBoxTCMemo.Text.Replace(str, "");
        }
        #endregion

        #region 报关

        /// <summary>
        /// 保存报关信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveBG_Click(object sender, EventArgs e)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            newSaveCustoms(sender, e);
        }

        private void btnAddHX_Click(object sender, EventArgs e)
        {
            TB_CheckOff c = new TB_CheckOff();
            c.backClientTime = DateTime.Now;
            c.backTime = DateTime.Now;

            if (this._DTHX != null && this._DTHX.Rows.Count > 0)
            {
                DataRow dr = this._DTHX.NewRow();
                OTConverter.ObjectPropertyToDataRow<TB_CheckOff>(c, this._DTHX.Columns, dr);
                this._DTHX.Rows.Add(dr);
                this._DTHX.AcceptChanges();
            }
            else
            {

                TB_CheckOff[] ary = new TB_CheckOff[] { c };
                this._DTHX = ary.ToDataTable();
                this.dgvHX.DataSource = this._DTHX;
            }

        }

        private void btnDeleteHX_Click(object sender, EventArgs e)
        {
            if (this.dgvHX.CurrentRow != null)
            {
                this._DTHX.Rows.RemoveAt(this.dgvHX.CurrentRow.Index);
                this._DTHX.AcceptChanges();
            }
        }

        private void btnClearBG_Click(object sender, EventArgs e)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (MessageBox.Show("确认删除报关信息吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                bool ok = this.BaseDataProxy.UpdateCustoms(this._Order.id, null);
                if (ok)
                    MessageBox.Show("报关信息已清除！");
                else
                    MessageBox.Show("报关信息清除失败！");
                clearTabPageFormInput(this.tabPage3);
            }
        }

        private void dgvHX_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dgvHX_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dgvHX_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 & e.ColumnIndex == 2)
            {

                var val = Convert.ToString(this.dgvHX.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                if (val == EnumCommon.CustomsStatus.已出退税.ToString())
                    this.cbBoxBGStatus.Text = val;
            }

        }


        private void ckBoxIsPass_Click(object sender, EventArgs e)
        {
            if (this.ckBoxIsPass.Checked)
                this.txtBoxBGPassTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            else
                this.txtBoxBGPassTime.Text = null;
        }

        private void btnPrintBGWTS_Click(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["OrderCodeHeader"] == "YH")
                PrintYHBGDPre();
        }
        #endregion

        #region 箱号货物管理
        private void btnAddXH_Click(object sender, EventArgs e)
        {
            //if (this._DTXH != null && this._DTXH.Rows.Count > 0)
            //{
            //    DataRow dr = this._DTXH.NewRow();
            //    this._DTXH.Rows.Add(dr);
            //    this._DTXH.AcceptChanges();
            //}
            //else
            //{
            //    TB_Case c = new TB_Case();
            //    TB_Case[] ary = new TB_Case[] { c };
            //    this._DTXH = ary.ToDataTable();
            //    this.dgvXH.DataSource = this._DTXH;
            //}           

            EditCaseFrm frm = new EditCaseFrm();
            frm.Order = this._Order;
            frm.Show(this);
        }

        private void btnDeleteXH_Click(object sender, EventArgs e)
        {
            if (dgvXH.CurrentRow != null)
                deleteXH(true, Convert.ToInt32(this.dgvXH.CurrentRow.Cells[0].Value));
        }

        /// <summary>
        /// 删除箱号事件
        /// </summary>
        /// <param name="serverDelete">是否从服务器删除</param>
        private void deleteXH(bool serverDelete, int id)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (serverDelete)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    this.BaseDataProxy.DeleteCase(id);
                else
                    return;
            }
            DataRow[] drs = this._DTXH.Select("id=" + id.ToString());
            foreach (DataRow dr in drs)
                _DTXH.Rows.Remove(dr);
            this._DTXH.AcceptChanges();

        }

        private void btnAddHW_Click(object sender, EventArgs e)
        {
            if (this.dgvXH.CurrentRow == null)
            {
                MessageBox.Show("请先选定货物所属箱号！");
                return;
            }

            //if (this.dgvXH.CurrentRow.Cells[1].Value == DBNull.Value || string.IsNullOrEmpty(this.dgvXH.CurrentRow.Cells[1].Value.ToString()))
            //{
            //    MessageBox.Show("所选输入的箱号不允许空！");
            //    return;
            //}
            //if (this.dgvXH.CurrentRow.Cells[2].Value == DBNull.Value || string.IsNullOrEmpty(this.dgvXH.CurrentRow.Cells[2].Value.ToString()))
            //{
            //    MessageBox.Show("所选输入的箱型不允许空！");
            //    return;
            //}

            //if (this._DTHW != null && this._DTHW.Rows.Count > 0)
            //{
            //    DataRow dr = this._DTHW.NewRow();
            //    this._DTHW.Rows.Add(dr);
            //    this._DTHW.AcceptChanges();
            //}
            //else
            //{
            //    TB_Cargo c = new TB_Cargo();
            //    TB_Cargo[] ary = new TB_Cargo[] { c };
            //    this._DTHW = ary.ToDataTable();
            //    this.dgvHW.DataSource = this._DTHW;
            //}            

            EditCargoFrm frm = new EditCargoFrm();
            frm.CaseID = Convert.ToInt32(this.dgvXH.CurrentRow.Cells[0].Value);
            frm.Order = this._Order;
            frm.ShowDialog(this);
        }

        private void btnDeleteHW_Click(object sender, EventArgs e)
        {
            if (this.dgvHW.CurrentRow != null)
                deleteHW(true, Convert.ToInt32(this.dgvHW.CurrentRow.Cells[0].Value));
        }

        /// <summary>
        /// 删除货号事件
        /// </summary>
        /// <param name="serverDelete">是否从服务器删除</param>
        private void deleteHW(bool serverDelete, int id)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (serverDelete)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    this.BaseDataProxy.DeleteCargo(id);
                else
                    return;
            }
            DataRow[] drs = this._DTHW.Select("id=" + id.ToString());
            foreach (DataRow dr in drs)
                this._DTHW.Rows.Remove(dr);
            this._DTHW.AcceptChanges();
        }

        private void dgvXH_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            EditCaseFrm frm = new EditCaseFrm();
            frm.ID = Convert.ToInt32(this.dgvXH.CurrentRow.Cells[0].Value);
            frm.Order = this._Order;
            frm.EditMode = true;
            frm.ShowDialog(this);
        }

        private void dgvHW_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            EditCargoFrm frm = new EditCargoFrm();
            frm.ID = Convert.ToInt32(this.dgvHW.CurrentRow.Cells[0].Value);
            frm.Order = this._Order;
            frm.EditMode = true;
            frm.ShowDialog(this);
        }

        private void dgvHW_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //判断要处理的DataGridViewComboBoxColumn名称，若符合条件，编辑控件被强制转换为ComboBox以处理，添加SelectedIndexChanged事件
            //if (this.dgvHW.CurrentCell.OwningColumn.Name == "packageType")
            //{
            //    ComboBox cb = (ComboBox)e.Control;
            //cb.DropDownStyle = ComboBoxStyle.DropDown;
            //cb.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
            //    Common.SelectedOptionsComboBox(cb, this.options, EnumCommon.OptionType.包装种类, null);
            // }

        }

        /// <summary>
        /// 箱号选定行改变触发，货物操作按钮可用状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvXH_SelectionChanged(object sender, EventArgs e)
        {
            getCargoInfo();
        }

        private void dgvHW_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvHW.RowCount > 0)
            {
                for (int i = 0; i < this.dgvHW.RowCount; i++)
                {
                    if (this.dgvHW.Rows[i].Cells[4].Value != null && this.dgvHW.Rows[i].Cells[4].Value != DBNull.Value)
                    {
                        TB_Options query = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.包装种类.ToString() && p.id == Convert.ToInt32(this.dgvHW.Rows[i].Cells[4].Value));
                        if (query != null)
                            this.dgvHW.Rows[i].Cells[5].Value = query.name;
                    }
                }

            }
        }

        private void dgvXH_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvXH_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dgvHW_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvHW_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        #endregion

        #region 文件上传下载
        private void btnUpload_Click(object sender, EventArgs e)
        {
            //if (Common.BIZ_OrderIsSubmit(this._Order.id))
            //{
            //    MessageBox.Show("已提交财务审核单据不能修改！");
            //    return;
            //}

            OpenFileDialog fileDialog = new OpenFileDialog();
            if ((fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK))
            {
                backgroundWorker1.RunWorkerAsync(fileDialog.FileName);
                this.progressBar.Visible = true;
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (this.dgvAttach.CurrentRow != null)
            {
                string ext = this.dgvAttach.CurrentRow.Cells[3].Value.ToString();
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = ext + "文件|*" + ext + "|所有文件|*.*";
                saveFileDialog.FilterIndex = 1;
                saveFileDialog.RestoreDirectory = true;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // get stream from server
                    System.IO.Stream inputStream;
                    int id = Convert.ToInt32(this.dgvAttach.CurrentRow.Cells[0].Value);
                    long len = this.BaseDataProxy.DownloadAttach(ref id, out inputStream);
                    this.progressBar.Visible = true;
                    using (System.IO.FileStream writeStream = new System.IO.FileStream(saveFileDialog.FileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
                    {
                        int chunkSize = 1024 * 10; //每次写入10k
                        byte[] buffer = new byte[chunkSize];
                        do
                        {
                            // read bytes from input stream
                            int bytesRead = inputStream.Read(buffer, 0, chunkSize);
                            if (bytesRead == 0) break;

                            // write bytes to output stream
                            writeStream.Write(buffer, 0, bytesRead);

                            // report progress from time to time
                            this.progressBar.Value = (int)(writeStream.Position * 100 / len);
                        } while (true);

                        // report end of progress
                        writeStream.Close();
                    }
                    this.progressBar.Visible = false;
                    // close service client
                    inputStream.Dispose();
                    System.Diagnostics.Process.Start("explorer.exe ", Path.GetDirectoryName(saveFileDialog.FileName));
                }
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int maxSiz = 1024 * 100;  //设置每次传100k 
            string fileName = e.Argument as string;

            using (FileStream stream = System.IO.File.OpenRead(fileName))    //读取本地文件
            {
                TransferFileInfo file = new TransferFileInfo();//this.BaseDataProxy.DownloadAttach(fileName);   //更加文件名,查询服务中是否存在该文件
                //if (file == null)     //表示文件不存在
                //{
                //    file = new TransferFileInfo();
                file.Offset = 0; //设置文件从开始位置进行数据传递
                //}
                file.Name = Path.GetFileName(fileName);
                file.Extension = Path.GetExtension(fileName);
                file.Length = stream.Length;
                file.CreateTime = DateTime.Now;

                if (file.Length == file.Offset) //如果文件的长度等于文件的偏移量，说明文件已经上传完成
                {
                    MessageBox.Show("该文件已经在服务器中,不用上传！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {

                    while (file.Length != file.Offset)  //循环的读取文件,上传，直到文件的长度等于文件的偏移量
                    {
                        file.Data = new byte[file.Length - file.Offset <= maxSiz ? file.Length - file.Offset : maxSiz]; //设置传递的数据的大小
                        stream.Position = file.Offset; //设置本地文件数据的读取位置
                        stream.Read(file.Data, 0, file.Data.Length);//把数据写入到file.Data中
                        file = this.BaseDataProxy.UploadAttach(file);     //上传

                        e.Result = file;
                        (sender as BackgroundWorker).ReportProgress((int)(((double)file.Offset / (double)((long)file.Length)) * 100), file.Offset);
                        if (this.backgroundWorker1.CancellationPending)
                            return;
                    }
                }
                stream.Close();
            }

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            { MessageBox.Show("操作进程取消！"); }
            else if (e.Error != null)
            { throw e.Error; }
            else
            {
                TransferFileInfo f = e.Result as TransferFileInfo;
                TB_Attach attach = new TB_Attach();
                attach.@operator = SysLoginUserInfo.UserId;
                attach.order = this._Order.id;
                attach.attachName = f.Name;
                attach.ext = f.Extension;
                attach.@operator = SysLoginUserInfo.UserId;
                attach.order = this._Order.id;
                attach.size = f.Length;
                attach.createTime = f.CreateTime;
                if (this.BaseDataProxy.AddAttach(attach) > 0)
                {
                    MessageBox.Show("文件已经成功上传！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    getAttachInfo();
                }
                else
                    MessageBox.Show("上传文件数据库写入失败！");
            }

            this.progressBar.Visible = false;

        }

        private void btnDeleteAttach_Click(object sender, EventArgs e)
        {
            if (Common.BIZ_OrderIsSubmit(this._Order.id))
            {
                MessageBox.Show("已提交财务审核单据不能修改！");
                return;
            }

            if (this.dgvAttach.CurrentRow != null)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (this.BaseDataProxy.DeleteAttach(Convert.ToInt32(this.dgvAttach.CurrentRow.Cells[0].Value)))
                    {
                        this._DTAttach.Rows.RemoveAt(this.dgvAttach.CurrentRow.Index);
                        this._DTAttach.AcceptChanges();
                    }
                }
            }
        }

        private void dgvAttach_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvAttach_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        #endregion

        #region 应收应付费用
        private void btnAddYS_Click(object sender, EventArgs e)
        {
            addFee(EnumCommon.FeeType.应收);
        }

        private void btnDeleteYS_Click(object sender, EventArgs e)
        {
            if (dgvYS.CurrentRow != null)
                deleteFee(this.dgvYS, true, this._DTYS, Convert.ToInt32(this.dgvYS.CurrentRow.Cells[1].Value));
        }

        private void addFee(EnumCommon.FeeType feeType)
        {
            EditFeeFrm frm = new EditFeeFrm();
            frm.Order = this._Order;
            frm.FeeType = feeType;
            frm.ShowDialog(this);
        }

        private void deleteFee(DataGridView dgv, bool serverDelete, DataTable dt, int id)
        {
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.财务员)
            {
                if (Common.BIZ_OrderIsClosed(this._Order.id))
                {
                    MessageBox.Show("已收款结束单据不能删除！");
                    return;
                }
            }
            else
            {
                if (Common.BIZ_OrderIsSubmit(this._Order.id))
                {
                    MessageBox.Show("已提交财务审核单据不能修改！");
                    return;
                }
            }

            if (serverDelete)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    this.BaseDataProxy.DeleteFee(id);
                else
                    return;
            }
            DataRow[] drs = dt.Select("id=" + id.ToString());
            foreach (DataRow dr in drs)
                dt.Rows.Remove(dr);
            dt.AcceptChanges();
        }

        private void btnAddYF_Click(object sender, EventArgs e)
        {
            addFee(EnumCommon.FeeType.应付);
        }

        private void btnDeleteYF_Click(object sender, EventArgs e)
        {
            if (dgvYF.CurrentRow != null)
                deleteFee(this.dgvYF, true, this._DTYF, Convert.ToInt32(this.dgvYF.CurrentRow.Cells[1].Value));
        }

        private void editFee(int id, EnumCommon.FeeType feeType)
        {
            EditFeeFrm frm = new EditFeeFrm();
            frm.ID = id;
            frm.EditMode = true;
            frm.Order = this._Order;
            frm.FeeType = feeType;
            frm.ShowDialog(this);
        }

        private void dgvYS_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            editFee(Convert.ToInt32(this.dgvYS.CurrentRow.Cells[1].Value), EnumCommon.FeeType.应收);
        }

        private void dgvYF_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            editFee(Convert.ToInt32(this.dgvYF.CurrentRow.Cells[1].Value), EnumCommon.FeeType.应付);
        }

        private void dgvYS_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            decimal total = 0;
            if (this.dgvYS.RowCount > 0)
            {
                for (int i = 0; i < this.dgvYS.RowCount; i++)
                {
                    if (!Common.IsDgvCellNull(this.dgvYS.Rows[i].Cells[2].Value))
                    {
                        TB_Options query = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.费目类型.ToString() && p.id == Convert.ToInt32(this.dgvYS.Rows[i].Cells[2].Value));
                        if (query != null)
                            this.dgvYS.Rows[i].Cells[3].Value = query.name;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYS.Rows[i].Cells[5].Value))
                    {
                        TB_Options query1 = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.币制单位.ToString() && p.id == Convert.ToInt32(this.dgvYS.Rows[i].Cells[5].Value));
                        if (query1 != null)
                            this.dgvYS.Rows[i].Cells[6].Value = query1.name;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYS.Rows[i].Cells[7].Value))
                    {
                        TB_Clients query2 = this.clients.SingleOrDefault(p => p.id == Convert.ToInt32(this.dgvYS.Rows[i].Cells[7].Value));
                        if (query2 != null)
                            this.dgvYS.Rows[i].Cells[8].Value = query2.fullName;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYS.Rows[i].Cells[4].Value))
                        total += Convert.ToDecimal(this.dgvYS.Rows[i].Cells[4].Value);
                }
            }
            this.txtBoxYSTotal.Text = total.ToString("f2");
            setLR();
        }

        private void dgvYF_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            decimal total = 0;
            if (this.dgvYF.RowCount > 0)
            {
                for (int i = 0; i < this.dgvYF.RowCount; i++)
                {
                    if (!Common.IsDgvCellNull(this.dgvYF.Rows[i].Cells[3].Value))
                    {
                        TB_Options query = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.费目类型.ToString() && p.id == Convert.ToInt32(this.dgvYF.Rows[i].Cells[3].Value));
                        if (query != null)
                            this.dgvYF.Rows[i].Cells[4].Value = query.name;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYF.Rows[i].Cells[6].Value))
                    {
                        TB_Options query1 = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.币制单位.ToString() && p.id == Convert.ToInt32(this.dgvYF.Rows[i].Cells[6].Value));
                        if (query1 != null)
                            this.dgvYF.Rows[i].Cells[7].Value = query1.name;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYF.Rows[i].Cells[2].Value))
                    {
                        TB_Options query2 = this.options.SingleOrDefault(p => p.type == EnumCommon.OptionType.结算对象.ToString() && p.id == Convert.ToInt32(this.dgvYF.Rows[i].Cells[2].Value));
                        if (query2 != null)
                            this.dgvYF.Rows[i].Cells[8].Value = query2.name;
                    }

                    if (!Common.IsDgvCellNull(this.dgvYF.Rows[i].Cells[5].Value))
                        total += Convert.ToDecimal(this.dgvYF.Rows[i].Cells[5].Value);
                }
            }
            this.txtBoxYFTotal.Text = total.ToString("f2");
            setLR();
        }

        /// <summary>
        /// 求利润
        /// </summary>
        void setLR()
        {
            var ys = Convert.ToDecimal(this.txtBoxYSTotal.Text);
            var yf = Convert.ToDecimal(this.txtBoxYFTotal.Text);
            this.txtBoxLRTotal.Text = (ys - yf).ToString("f2");
        }

        private void dgvYS_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvYS_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvYF_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        private void dgvYF_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }
        #endregion

        private void dgvWorkflow_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dgvWorkflow_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            YY.Common.EventCommon.CaseUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateXHDgv);
            YY.Common.EventCommon.CargoUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateHWDgv);
            YY.Common.EventCommon.YSUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateYSDgv);
            YY.Common.EventCommon.YFUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateYFDgv);
            YY.Common.EventCommon.WorkFlowUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateWorkflow);
        }
        #endregion


        void printYYTCWTS()
        {
            if (this._Trailer == null)
                return;
            ExcelCommon excel = new ExcelCommon();
            try
            {
                excel.Create();
                excel.ws = excel.AddSheet("sh1");
                excel.app.Visible = true;

                excel.SetCellValue(excel.ws, 1, 1, "广州市盈洋货运代理有限公司");///row1
                //excel.UniteCells(excel.ws, 1, 1, 1, 1);
                excel.SetCellProperty(excel.ws, 1, 1, 1, 1, 30, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlCenter, false);

                excel.SetCellValue(excel.ws, 3, 1, "派车委托书");//row3
                //excel.UniteCells(excel.ws, 3, 1, 3, 1);
                excel.SetCellProperty(excel.ws, 3, 1, 3, 1, 20, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlCenter, false);

                //TB_Clients c = this.clients.Single(p => p.id == this._Order.client);
                excel.SetCellValue(excel.ws, 4, 1, "致" + this.options.SingleOrDefault(p => p.id == this._Trailer.agent).name + " " + this._Trailer.stowageContact);//row4
                //excel.UniteCells(excel.ws, 4, 1, 4, 5);
                //excel.SetCellProperty(excel.ws, 4, 1, 4, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);                

                excel.SetCellValue(excel.ws, 5, 1, "兹委托贵公司派车到以下地点装货，资料如下：");//row5
                //excel.UniteCells(excel.ws, 5, 1, 5, 5);
                //excel.SetCellProperty(excel.ws, 5, 1, 5, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);                

                excel.SetCellValue(excel.ws, 6, 1, "1、订舱号：" + this._Order.cCode);//row6
                //excel.UniteCells(excel.ws, 6, 1, 6, 5);
                //excel.SetCellProperty(excel.ws, 6, 1, 6, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);                

                string deadLineTime = string.Empty;
                if (this._Trailer.deadline != null)
                    deadLineTime = Convert.ToDateTime(this._Trailer.deadline).ToString("g");
                excel.SetCellValue(excel.ws, 7, 1, "到厂装货时间：" + deadLineTime);//row7
                //excel.UniteCells(excel.ws, 7, 1, 7, 5);
                //excel.SetCellProperty(excel.ws, 7, 1, 7, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);                

                excel.SetCellValue(excel.ws, 8, 1, "2、装货地点：" + this._Trailer.address);//row8
                //excel.UniteCells(excel.ws, 8, 1, 8, 5);
                //excel.SetCellProperty(excel.ws, 8, 1, 8, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);                

                excel.SetCellValue(excel.ws, 9, 1, "3、联系人：" + this._Trailer.stowageContact);//row9
                //excel.UniteCells(excel.ws, 9, 1, 9, 5);
                //excel.SetCellProperty(excel.ws, 9, 1, 9, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);                

                excel.SetCellValue(excel.ws, 10, 1, "4、柜型：" + this._Trailer.specs);//row10
                //excel.UniteCells(excel.ws, 10, 1, 10, 10);
                //excel.SetCellProperty(excel.ws, 10, 1, 10, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);

                string charge = string.Empty;
                if (this._Trailer.charge != null)
                    charge = Convert.ToDecimal(this._Trailer.charge).ToString();
                excel.SetCellValue(excel.ws, 11, 1, "5、运费：" + charge);//row11
                //excel.UniteCells(excel.ws, 11, 1, 11, 10);
                //excel.SetCellProperty(excel.ws, 11, 1, 11, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);

                excel.SetCellValue(excel.ws, 12, 1, "6、备注：" + this._Trailer.memo);//row12
                //excel.UniteCells(excel.ws, 12, 1, 12, 10);
                //excel.SetCellProperty(excel.ws, 12, 1, 12, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);

                excel.SetCellValue(excel.ws, 13, 1, "7、（请准时到达。柜号司机资料麻烦到时发到15018476677 谢谢！）");//row13
                //excel.UniteCells(excel.ws, 13, 1, 13, 10);
                //excel.SetCellProperty(excel.ws, 13, 1, 13, 5, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, true);


                TB_User op = this.bizMans.SingleOrDefault(p => p.id == this._Order.agent);
                excel.SetCellValue(excel.ws, 15, 1, "操作人员：" + op.userName);//row4 col6
                //excel.UniteCells(excel.ws, 4, 7, 4, 10);
                //excel.SetCellProperty(excel.ws, 4, 7, 4, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellValue(excel.ws, 16, 1, "我司单号：" + this._Order.code);//row5 col6
                //excel.UniteCells(excel.ws, 5, 7, 5, 10);
                //excel.SetCellProperty(excel.ws, 5, 7, 5, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellValue(excel.ws, 17, 1, "座机号：020-28945185");//row6 col6
                //excel.UniteCells(excel.ws, 6, 7, 6, 10);
                //excel.SetCellProperty(excel.ws, 6, 7, 6, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellValue(excel.ws, 18, 1, "手机：" + op.tel);//row7 col6
                //excel.UniteCells(excel.ws, 7, 7, 7, 10);
                //excel.SetCellProperty(excel.ws, 7, 7, 7, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellValue(excel.ws, 19, 1, "传真号：020-32372253");//row8 col6
                //excel.UniteCells(excel.ws, 8, 7, 8, 10);
                //excel.SetCellProperty(excel.ws, 8, 7, 8, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellValue(excel.ws, 20, 1, "日期：" + DateTime.Now.ToString("yyyy-MM-dd"));//row9 col6
                //excel.UniteCells(excel.ws, 9, 7, 9, 10);
                //excel.SetCellProperty(excel.ws, 9, 7, 9, 10, 12, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);

                excel.SetCellProperty(excel.ws, 4, 1, 20, 1, 15, true, "宋体", Microsoft.Office.Interop.Excel.Constants.xlColor3, Microsoft.Office.Interop.Excel.Constants.xlLeft, false);
                excel.ColumnsAutoFit(excel.ws, 1, 1, 20, 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                excel.Dispose();
            }
            finally
            {

            }
        }

        #region 生成Excel

        void printYHPCDPre()
        {
            var provider = this.options.SingleOrDefault(p => p.id == this._Trailer.agent);
            var op = this.bizMans.SingleOrDefault(p => p.id == this._Order.agent);
            var feeItem = this.options.SingleOrDefault(p => p.name == "拖车费" & p.type == EnumCommon.OptionType.费目类型.ToString());

            if (feeItem == null)
            {
                MessageBox.Show("没找到[拖车费]费目数据！");
                return;
            }

            decimal fee = 0;
            var fees = this.BaseDataProxy.FindFees(this._Order.code, null, null, null, null, null, (int)EnumCommon.FeeType.应付, null, feeItem.id, null, null);
            if (fees != null)
            {
                foreach (var f in fees)
                    fee += f.Amount;

            }

            var deadline = string.Empty;
            //if (this._Trailer.deadline.HasValue)
            //deadline = this._Trailer.deadline.Value.ToString("yyyy-MM-dd hh:mm");
            deadline = this._Trailer.deadline;
            var zgAddress = this._Trailer.address;
            var zgContact = this._Trailer.stowageContact;
            var returnPort = string.Empty;
            if (this._Trailer.returnPort.HasValue)
                returnPort = this.options.SingleOrDefault(p => p.id == this._Trailer.returnPort.Value).name;
            var tcMemo = this._Trailer.memo;
            PrintYHPCD("广州市盈泓货运代理有限公司", provider.name, op.userName, op.tel, op.mobile, this._Order.code, this._Order.cCode, this._Trailer.specs, fee.ToString("N2"), tcMemo, deadline, zgAddress, zgContact, returnPort);

        }

        void PrintYHPCD(string comTitle, string providerName, string opName, string opTel, string opMobile, string orderCode, string dcCode, string gx, string tcFee, string tcMemo, string deadline, string zgAddress, string zgContact, string returnPort)
        {
            ExcelXmlWorkbook book = new ExcelXmlWorkbook();
            //string rtn = string.Empty;
            try
            {

                book.Properties.Author = "盈泓";
                Worksheet sheet = book[0];
                sheet.Name = "派车单";

                // and this too...
                sheet.PrintOptions.Orientation = PageOrientation.Portrait;
                sheet.PrintOptions.SetMargins(0.5, 0.4, 0.5, 0.4);


                XmlStyle style21 = new XmlStyle();
                style21.Alignment.Vertical = VerticalAlignment.Bottom;


                XmlStyle styles22 = new XmlStyle();
                styles22.Font.Size = 16;
                styles22.Font.Name = "宋体";

                XmlStyle styles23 = new XmlStyle();
                styles23.Font.Size = 18;
                styles23.Font.Name = "宋体";

                XmlStyle styles35 = new XmlStyle();
                styles35.Font.Size = 18;
                styles35.Font.Name = "宋体";
                styles35.Alignment.Vertical = VerticalAlignment.Bottom;
                styles35.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;

                XmlStyle styles36 = new XmlStyle();
                styles36.Font.Size = 14;
                styles36.Font.Name = "Times New Roman";
                styles36.Alignment.Vertical = VerticalAlignment.Bottom;
                styles36.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                styles36.Font.Bold = true;

                XmlStyle styles37 = new XmlStyle();
                styles37.Font.Size = 12;
                styles37.Font.Name = "宋体";
                styles37.Alignment.Vertical = VerticalAlignment.Bottom;
                styles37.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                styles37.Font.Bold = true;
                styles37.Border.LineStyle = Borderline.Double;
                styles37.Border.Weight = 3;
                styles37.Border.Sides = BorderSides.Bottom;

                XmlStyle styles38 = new XmlStyle();
                styles38.Font.Size = 18;
                styles38.Font.Name = "宋体";
                styles38.Alignment.Vertical = VerticalAlignment.Bottom;
                styles38.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;
                styles38.Alignment.WrapText = true;

                XmlStyle styles39 = new XmlStyle();
                styles39.Font.Size = 16;
                styles39.Font.Name = "宋体";
                styles39.Alignment.Vertical = VerticalAlignment.Bottom;
                styles39.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;

                XmlStyle styles40 = new XmlStyle();
                styles40.Alignment.Vertical = VerticalAlignment.Bottom;
                styles40.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;

                XmlStyle styles41 = new XmlStyle();
                styles41.Font.Size = 18;
                styles41.Font.Name = "宋体";
                styles41.Alignment.Vertical = VerticalAlignment.Center;
                styles41.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;
                styles41.Alignment.WrapText = true;

                XmlStyle styles42 = new XmlStyle();
                styles42.Font.Size = 24;
                styles42.Font.Name = "宋体";
                styles42.Font.Bold = true;
                styles42.Alignment.Vertical = VerticalAlignment.Justify;
                styles42.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                styles42.Alignment.WrapText = true;

                XmlStyle styles43 = new XmlStyle();
                styles43.Font.Size = 24;
                styles43.Font.Name = "宋体";
                styles43.Font.Bold = true;
                styles43.Alignment.Vertical = VerticalAlignment.Center;
                styles43.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                styles43.Border.LineStyle = Borderline.Double;
                styles43.Border.Weight = 3;
                styles43.Border.Sides = BorderSides.Top;

                XmlStyle styles45 = new XmlStyle();
                styles45.Font.Size = 18;
                styles45.Font.Name = "宋体";
                styles45.Alignment.Vertical = VerticalAlignment.Bottom;
                styles45.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;

                sheet[0, 0].Value = comTitle;
                sheet[0, 0].Style = styles42;

                sheet[0, 1].Value = "GUANGZHOU YINGHONG LOGISTICS CO.,LTD";
                sheet[0, 1].Style = styles36;

                sheet[0, 2].Value = "地址Add：广州市黄埔区骏雅北街3号金碧领秀国际商务中心804房";
                sheet[0, 2].Style = styles37;

                sheet[0, 3].Value = "派车单";
                sheet[0, 3].Style = styles43;

                sheet[0, 4].Value = "TO:" + providerName;
                sheet[0, 4].Style = styles38;

                sheet[0, 5].Value = "FM:盈泓/" + opName + "   " + opTel;//客服名称 电话
                sheet[0, 5].Style = styles38;

                sheet[0, 6].Value = "";
                sheet[0, 6].Style = styles35;

                sheet[0, 7].Value = "我司单号:" + orderCode;
                sheet[0, 7].Style = styles38;

                sheet[0, 8].Value = "";
                sheet[0, 8].Style = styles35;

                sheet[0, 9].Value = "订 舱 号:" + dcCode;//提单号
                sheet[0, 9].Style = styles38;

                sheet[0, 10].Value = "柜    型：" + gx;
                sheet[0, 10].Style = styles38;

                sheet[0, 11].Value = "";
                sheet[0, 11].Style = styles45;

                sheet[0, 12].Value = "装柜时间：" + deadline;
                sheet[0, 12].Style = styles38;

                sheet[0, 13].Value = "";
                sheet[0, 13].Style = styles40;

                sheet[0, 14].Value = "装柜地点：" + zgAddress + " " + zgContact;
                sheet[0, 14].Style = styles38;

                sheet[0, 15].Value = "";
                sheet[0, 15].Style = styles39;

                sheet[0, 16].Value = "";
                sheet[0, 16].Style = styles41;

                sheet[0, 17].Value = "";
                sheet[0, 17].Style = styles35;

                sheet[0, 18].Value = "还柜码头:" + returnPort;
                sheet[0, 18].Style = styles38;

                sheet[0, 19].Value = "拖车备注:" + tcMemo;
                sheet[0, 19].Style = styles38;

                sheet[0, 20].Value = "";
                sheet[0, 20].Style = styles35;

                sheet[0, 21].Value = "";
                sheet[0, 21].Style = styles35;

                sheet[0, 22].Value = "柜号请发到我司联系人/手机：" + opName + "  " + opMobile;
                sheet[0, 22].Style = styles38;

                sheet[0, 23].Value = "费用确认：RMB" + tcFee;
                sheet[0, 23].Style = styles38;

                sheet[0, 24].Value = "";
                sheet[0, 24].Style = styles35;

                sheet[0, 25].Value = "如有实报实销的费用请在拖车完成后及时回传！";
                sheet[0, 25].Style = styles23;

                sheet[0, 26].Value = "请及时安排！";
                sheet[0, 26].Style = styles35;

                sheet[0, 27].Value = "";
                sheet[0, 27].Style = styles35;

                sheet[0, 28].Value = "合作愉快！TKS！";
                sheet[0, 28].Style.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Right;
                sheet[0, 28].Style.Font.Size = 18;
                sheet[0, 28].Style.Font.Name = "宋体";

                sheet.Columns(0).Width = 500;
                //sheet.Columns(0).Style.Alignment.ShrinkToFit = true; ;
                for (int i = 0; i <= 28; i++)
                    sheet[i].Style.Alignment.ShrinkToFit = true;

                // no extension is added if not present
                //string outputFile = "Outstanding File.xml";

                //book.Export(contextResponse.OutputStream);
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Excel文件|*.xls|XML数据|*.xml";
                saveFileDialog.RestoreDirectory = true;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    book.Export(saveFileDialog.FileName);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void PrintYHBGDPre()
        {
            if (this._DTXH == null)
            {
                //加载箱号
                this._DTXH = this.BaseDataProxy.GetCases(this._Order.id).ToDataTable();
            }

            var bgAgent = this.options.SingleOrDefault(p => p.id == this._Customs.agent);
            var op = this.bizMans.SingleOrDefault(p => p.id == this._Order.agent);
            var startPort = this.options.SingleOrDefault(p => p.id == this._Order.startPort).name;
            var jgTime = string.Empty;
            if (this._Order.customsDeadline.HasValue)
                jgTime = this._Order.customsDeadline.Value.ToString("yyyy-MM-dd");
            var trasferType = string.Empty;
            if (this._Customs.transferType.HasValue)
                trasferType = this.options.SingleOrDefault(p => p.id == this._Customs.transferType.Value).name;
            var zgxs = string.Empty;
            if (this._Order.stowageMethod.HasValue)
                zgxs = this.options.SingleOrDefault(p => p.id == this._Order.stowageMethod.Value).name;
            var bgMemo = this._Customs.memo;
            List<string[]> cargos = new List<string[]>();
            if (this._DTXH != null)
            {
                foreach (DataRow xh in this._DTXH.Rows)
                {
                    //加载货物
                    var goods = this.BaseDataProxy.GetCargos(Convert.ToInt32(xh[0])).ToDataTable();
                    if (goods != null)
                    {
                        foreach (DataRow dr in goods.Rows)
                        {
                            DataRow[] rs = this._DTXH.Select("id=" + dr.Field<int>("case").ToString());
                            if (rs != null)
                            {
                                var ss = rs[0].Field<string>("code") + "/" + rs[0].Field<string>("model");
                                cargos.Add(new string[] { ss, rs[0].Field<string>("title"), dr.Field<string>("amount"), dr.Field<string>("hairWeight"), dr.Field<string>("cargoName") });
                            }
                        }
                    }
                }
            }

            decimal fee = 0;
            var feeItem = this.options.SingleOrDefault(p => p.name == "报关费" & p.type == EnumCommon.OptionType.费目类型.ToString());
            var fees = this.BaseDataProxy.FindFees(this._Order.code, null, null, null, null, null, (int)EnumCommon.FeeType.应付, null, feeItem.id, null, null);
            if (fees != null)
            {
                foreach (var f in fees)
                    fee += f.Amount;

            }
            PrintYHBGD("广州市盈泓货运代理有限公司", bgAgent.name, op.userName, op.tel, this._Order.code, this._Order.cCode, startPort, jgTime, this._Customs.address, trasferType, zgxs, cargos, fee.ToString("N2"), bgMemo);
        }

        void PrintYHBGD(string comTitle, string bgAgent, string opName, string opTel, string orderCode, string cCode, string startPort, string jgTime, string fxtAddress, string transferType, string zgxs, List<string[]> cargos, string fee, string memo)
        {
            ExcelXmlWorkbook book = new ExcelXmlWorkbook();
            try
            {
                book.Properties.Author = "盈泓";
                Worksheet sheet = book[0];
                sheet.Name = "报关委托书";

                sheet.PrintOptions.Orientation = PageOrientation.Landscape;
                sheet.PrintOptions.SetMargins(0.5, 0.4, 0.5, 0.4);


                XmlStyle m24864368 = new XmlStyle();
                m24864368.Alignment.Vertical = VerticalAlignment.Bottom;
                m24864368.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                m24864368.Border.LineStyle = Borderline.Continuous;
                m24864368.Border.Weight = 1;
                m24864368.Border.Sides = BorderSides.All;

                XmlStyle s21 = new XmlStyle();

                XmlStyle s22 = new XmlStyle();//s48
                s22.Alignment.Vertical = VerticalAlignment.Bottom;

                XmlStyle s25 = new XmlStyle();
                s25.Alignment.Vertical = VerticalAlignment.Bottom;
                s25.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                s25.Border.LineStyle = Borderline.Continuous;
                s25.Border.Weight = 1;
                s25.Border.Sides = BorderSides.All;
                s25.Font.Name = "宋体";
                s25.Font.Size = 16;

                XmlStyle s45 = new XmlStyle();
                s45.Alignment.Vertical = VerticalAlignment.Bottom;
                s45.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;

                XmlStyle s46 = new XmlStyle();
                s46.Alignment.Vertical = VerticalAlignment.Bottom;
                s46.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Left;
                s46.Font.Name = "宋体";
                s46.Font.Size = 16;

                XmlStyle s47 = new XmlStyle();
                s47.Alignment.Vertical = VerticalAlignment.Bottom;
                s47.Font.Name = "宋体";
                s47.Font.Size = 16;

                XmlStyle s51 = new XmlStyle();
                s51.Alignment.Vertical = VerticalAlignment.Bottom;
                s51.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                s51.Font.Name = "楷体_GB2312";
                s51.Font.Size = 20;
                s51.Font.Bold = true;

                XmlStyle s52 = new XmlStyle();
                s52.Alignment.Vertical = VerticalAlignment.Bottom;
                s52.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                s52.Border.Sides = BorderSides.Bottom;
                s52.Border.LineStyle = Borderline.Double;
                s52.Border.Weight = 3;
                s52.Font.Name = "Arial";
                s52.Font.Size = 12;
                s52.Font.Bold = true;

                XmlStyle s53 = new XmlStyle();
                s53.Alignment.Vertical = VerticalAlignment.Bottom;
                s53.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                s53.Border.Sides = BorderSides.Top;
                s53.Border.LineStyle = Borderline.Double;
                s53.Border.Weight = 3;
                s53.Font.Name = "宋体";
                s53.Font.Size = 22;
                s53.Font.Bold = true;

                XmlStyle s54 = new XmlStyle();
                s54.Alignment.Vertical = VerticalAlignment.Bottom;
                s54.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;
                s54.Font.Name = "宋体";
                s54.Font.Size = 16;

                XmlStyle s61 = new XmlStyle();
                s61.Alignment.Vertical = VerticalAlignment.Bottom;
                s61.Alignment.Horizontal = Yogesh.ExcelXml.HorizontalAlignment.Center;

                sheet[0, 0].Value = comTitle;
                sheet[0, 0].Style = s51;
                new Range(sheet[0, 0], sheet[7, 0]).Merge();

                sheet[0, 1].Value = "GUANGZHOU  YINGHONG  LOGISTICS  CO.,LTD";
                sheet[0, 1].Style = s52;
                new Range(sheet[0, 1], sheet[7, 1]).Merge();

                sheet[0, 2].Value = "报关委托书";
                sheet[0, 2].Style = s53;
                new Range(sheet[0, 2], sheet[7, 2]).Merge();

                sheet[0, 3].Value = "TO：" + bgAgent;
                sheet[0, 3].Style = s46;
                new Range(sheet[0, 3], sheet[7, 3]).Merge();

                sheet[0, 4].Value = "FM：盈泓/" + opName + "   " + opTel;
                sheet[0, 4].Style = s46;
                new Range(sheet[0, 4], sheet[7, 4]).Merge();

                sheet[0, 5].Value = "";
                sheet[0, 5].Style = s54;
                new Range(sheet[0, 5], sheet[7, 5]).Merge();

                sheet[0, 6].Value = "我司单号：" + orderCode;
                sheet[0, 6].Style = s46;
                new Range(sheet[0, 6], sheet[7, 6]).Merge();

                sheet[0, 7].Value = "订 舱 号：" + cCode;
                sheet[0, 7].Style = s46;
                new Range(sheet[0, 7], sheet[7, 7]).Merge();

                sheet[0, 8].Value = "起运码头：" + startPort;
                sheet[0, 8].Style = s46;
                new Range(sheet[0, 8], sheet[7, 8]).Merge();

                sheet[0, 9].Value = "截关时间：" + jgTime;
                sheet[0, 9].Style = s46;
                new Range(sheet[0, 9], sheet[7, 9]).Merge();

                sheet[0, 10].Value = "交放行条地址：" + fxtAddress;
                sheet[0, 10].Style = s46;
                new Range(sheet[0, 10], sheet[7, 10]).Merge();

                sheet[0, 11].Value = "报关备注：" + (string.IsNullOrEmpty(memo) ? "外拖/国际中转" : memo);//transferType + "/" + zgxs;
                sheet[0, 11].Style = s46;
                new Range(sheet[0, 11], sheet[7, 11]).Merge();

                sheet[0, 12].Value = "";
                sheet[0, 12].Style = s46;
                new Range(sheet[0, 12], sheet[7, 12]).Merge();

                sheet[0, 13].Value = "货物清单：";
                sheet[0, 13].Style = s46;
                new Range(sheet[0, 13], sheet[7, 13]).Merge();

                sheet[0, 14].Value = "柜号/柜型";
                sheet[0, 14].Style = s25;
                new Range(sheet[0, 14], sheet[2, 14]).Merge();

                sheet[3, 14].Value = "封号";
                sheet[3, 14].Style = s25;
                new Range(sheet[3, 14], sheet[4, 14]).Merge();

                sheet[5, 14].Value = "数量";
                sheet[5, 14].Style = s25;

                sheet[6, 14].Value = "毛重";
                sheet[6, 14].Style = s25;

                sheet[7, 14].Value = "货名";
                sheet[7, 14].Style = s25;
                var index = 15;
                for (var i = 0; i < cargos.Count; i++)
                {
                    sheet[0, index].Value = cargos[i][0];
                    sheet[0, index].Style = s25;
                    new Range(sheet[0, index], sheet[2, index]).Merge();

                    sheet[3, index].Value = cargos[i][1];
                    sheet[3, index].Style = s25;
                    new Range(sheet[3, index], sheet[4, index]).Merge();

                    sheet[5, index].Value = cargos[i][2];
                    sheet[5, index].Style = s25;

                    sheet[6, index].Value = cargos[i][3];
                    sheet[6, index].Style = s25;

                    sheet[7, index].Value = cargos[i][4];
                    sheet[7, index].Style = s25;
                    index++;
                }

                sheet[0, index].Value = "费用确认：" + fee + "元";
                sheet[0, index].Style = s47;
                new Range(sheet[0, index], sheet[7, index]).Merge();

                index++;
                sheet[0, index].Value = "";
                sheet[0, index].Style = s47;
                new Range(sheet[0, index], sheet[7, index]).Merge();

                index++;
                sheet[0, index].Value = "请尽快安排报关!放行后请通知我司！";
                sheet[0, index].Style = s46;
                new Range(sheet[0, index], sheet[7, index]).Merge();

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Excel文件|*.xls|XML数据|*.xml";
                saveFileDialog.RestoreDirectory = true;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    book.Export(saveFileDialog.FileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 费用审批
        /// </summary>
        /// <param name="isVerify">是否批准</param>
        /// <returns></returns>
        private bool verifyFee(bool isVerify)
        {
            if (this._Fee != null)
            {
                this._Fee.isVerify = isVerify;
                this._Fee.verifyMan = SysLoginUserInfo.UserId;
                this._Fee.verifyTime = DateTime.Now;
                if (this.BaseDataProxy.UpdateFee(this._Fee))
                    return true;
            }
            return false;
        }

        private void btnBatchApproveAP_Click(object sender, EventArgs e)
        {
            string msg = "批准";
            if (MessageBox.Show("确认" + msg + "该费用吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var ids = new List<int>();
                for (int i = 0; i < this.dgvYS.RowCount; i++)
                {
                    if (this.dgvYS.Rows[i].Cells[0].Value != null && this.dgvYS.Rows[i].Cells[0].Value.ToString().Equals("True"))
                    {
                        ids.Add(Convert.ToInt32(this.dgvYS.Rows[i].Cells[1].Value));
                    }
                }
                ids.ForEach(
                    p =>
                    {
                        this._Fee = this.BaseDataProxy.GetFee(p);
                        if (_Fee != null && verifyFee(!this._Fee.isVerify))
                        {
                            CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(this._Fee, Common.OperateType.Update);
                            YY.Common.EventCommon.OnYSUdDGVEvnt(sender, arg);
                        }
                        else
                        {
                            MessageBox.Show("费用审批失败");
                            return;
                        }
                    });

                MessageBox.Show("费用已" + msg);
            }
        }

        private void btnBatchApproveAR_Click(object sender, EventArgs e)
        {
            string msg = "批准";
            if (MessageBox.Show("确认" + msg + "该费用吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var ids = new List<int>();
                for (int i = 0; i < this.dgvYF.RowCount; i++)
                {
                    if (this.dgvYF.Rows[i].Cells[0].Value != null && this.dgvYF.Rows[i].Cells[0].Value.ToString().Equals("True"))
                    {
                        ids.Add(Convert.ToInt32(this.dgvYF.Rows[i].Cells[1].Value));
                    }
                }

                ids.ForEach(
                    p =>
                    {
                        this._Fee = this.BaseDataProxy.GetFee(Convert.ToInt32(p));
                        if (_Fee != null && verifyFee(!this._Fee.isVerify))
                        {
                            CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(this._Fee, Common.OperateType.Update);
                            YY.Common.EventCommon.OnYFUdDGVEvnt(sender, arg);
                        }
                        else
                        {
                            MessageBox.Show("费用审批失败");
                            return;
                        }
                    });
                MessageBox.Show("费用已" + msg);
            }
        }

        private void btnBackTax_Click(object sender, EventArgs e)
        {
            this.cbBoxBGStatus.Text = EnumCommon.CustomsStatus.已出退税.ToString();
            newSaveCustoms(sender, e);

        }

        void newSaveCustoms(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.cbBoxBGStatus.Text))
            {
                MessageBox.Show("请选择报关状态！");
                this.cbBoxBGStatus.Focus();
                return;
            }

            if (this.cbBoxBGAgent.SelectedItem == null)
            {
                MessageBox.Show("请选择报关行！");
                this.cbBoxBGAgent.Focus();
                return;
            }

            TB_Customs customs = new TB_Customs();
            customs.isCheck = this.ckBoxIsCheck.Checked;
            customs.isDrawback = this.ckBoxIsDrawback.Checked;
            customs.isKdsk = this.ckBoxIsKdsk.Checked;
            customs.isNotice = this.ckBoxNotice.Checked;
            customs.isOffer = this.ckBoxIsOffer.Checked;
            customs.isPass = this.ckBoxIsPass.Checked;
            customs.memo = this.txtBoxBGMemo.Text;
            customs.notifier = this.txtBoxNotifier.Text;
            //customs.order = this._Order.id;
            customs.receiver = this.txtBoxReceiver.Text;
            customs.runNum = this.txtBoxRunNum.Text;
            customs.status = this.cbBoxBGStatus.Text;
            customs.stockholder = this.txtBoxStockholder.Text;
            if (this.cbBoxTransferType.SelectedItem != null)
                customs.transferType = (this.cbBoxTransferType.SelectedItem as TB_Options).id;
            customs.address = this.txtBoxBGAddress.Text;
            customs.agent = (this.cbBoxBGAgent.SelectedItem as TB_Options).id;
            customs.applyDate = this.dtpApplyDate.Value;
            customs.boatCorp = this.txtBoxBoatCorp.Text;
            customs.boatName = this.txtBoxBoatName.Text;
            customs.bookingMemo = this.txtBoxBookingMemo.Text;
            //customs.code = this.txtBoxBGCode.Text;
            if (!string.IsNullOrEmpty(this.txtBoxBGPassTime.Text))
                customs.passTime = Convert.ToDateTime(this.txtBoxBGPassTime.Text);
            customs.contactMan = this.txtBoxBGContactMan.Text;
            customs.contactTel = this.txtBoxBGTel.Text;
            customs.demand = this.txtBoxDemand.Text;
            customs.destination = this.txtBoxDestination.Text;
            if (this.cbBoxEndPort.SelectedItem != null)
                customs.endPort = (this.cbBoxEndPort.SelectedItem as TB_Options).id;
            if (this._DTHX != null && this._DTHX.Rows.Count > 0)
                customs.TB_CheckOff = OTConverter.ConvertTableToObject<TB_CheckOff>(this._DTHX).ToArray();
            bool ok = false;
            ok = this.BaseDataProxy.UpdateCustoms(this._Order.id, new TB_Customs[] { customs });
            if (ok)
            {
                Common.OperateType opType = Common.OperateType.Update;
                CommonEventArg<TB_Order> arg = new CommonEventArg<TB_Order>(this._Order, opType);
                YY.Common.EventCommon.OnOrderUdDGVEvnt(sender, arg);
                this._Customs.memo = customs.memo;
                MessageBox.Show("报关信息已保存！");
            }
            else
                MessageBox.Show("报关信息保存失败！");
        }


    }
}